<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="params.agency_name" placeholder="机构名称"></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          :auto-top="1"
          @change="getData()"
          placeholder="地址查询"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <select-org-bank
          v-model="seachBankId"
          placeholder="选择银行"
          filterable
          clearable
          @select="selectBank"
        ></select-org-bank>
      </el-form-item>
      <!-- <el-form-item>
        <c-select
          v-model="params['access_status.eq']"
          placeholder="准入状态"
          @change="getData()"
          clearable
          :options="enumAccessStatus"
        ></c-select>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="getData()" :loading="loading">查询</el-button>
      </el-form-item>
    </el-form>
    <c-table
      border
      class="table-sm"
      v-loading="loading"
      :columns="tableColumns"
      :data="tableData"
      row-key="credit_agency_access_id"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>
      <template v-slot:status="scope">
        <span class="badge" :class="`badge-${scope.row.access_style}`">
          {{ scope.row.access_label }}
        </span>
      </template>
      <template v-slot:detail="scope">
        <span v-if="!+scope.row.access_detail_count">-</span>
        <el-button v-else @click="handleDetail(scope.row)" type="text">
          {{ scope.row.access_detail_count }}
        </el-button>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <bank-view :visible.sync="infoVisible" :type="type" :accessInfo="accessInfo"></bank-view>

    <select-access-bank-dialog
      :visible.sync="newVisible"
      width="80%"
      :disabled-node="disabledNode"
      v-model="newBankIds"
      @save="handleSubmit"
    ></select-access-bank-dialog>

    <edit-org
      :visible.sync="editVisible"
      @success="getData(params.index)"
      orgType="1"
      :formData="bankInfo"
      :tableId="bankId"
    ></edit-org>
    <bank-branch :visible.sync="detailVisible" :query-id="queryId"></bank-branch>

    <bank-approval
      :visible.sync="approvalVisible"
      :type="type"
      @success="getData(params.index)"
      :form-data="approvalData"
    ></bank-approval>
  </div>
</template>

<script>
import SelectAddress from '@/components/select/SelectAddress'
import { mapGetters } from 'vuex'
import { enumAccessStatus, enumAccessStatusLabel } from '@/credit/plugins/enumTown'
import BankView from '@/credit/views/org/BankView'
import SelectAccessBankDialog from '@/credit/components/select/SelectAccessBankDialog'
import EditOrg from '@/credit/views//org/NewOrg'
import BankBranch from '@/credit/views/org/BankBranch'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import BankApproval from '@/credit/views/org/BankApproval'
export default {
  props: {
    type: String,
  },
  components: {
    SelectAddress,
    BankView,
    SelectAccessBankDialog,
    EditOrg,
    BankBranch,
    SelectOrgBank,
    BankApproval,
  },
  data() {
    return {
      enumAccessStatus,
      params: {
        index: 1,
        size: 15,
        'agency_type.eq': 1,
        address_code: '',
        agency_name: '',
      },
      order: {
        create_time: 'desc',
      },
      loading: false,
      tableData: [],
      tableName: 'credit_agency_access_bank_view',
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            reserveSelection: true,
          },
        },
        { attrs: { label: '机构名称', prop: 'agency_name' } },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        { attrs: { label: '联系人', prop: 'contact' } },
        { attrs: { label: '联系电话', prop: 'mobile_no' } },
        // { attrs: { label: '准入状态', prop: 'access_label', align: 'center' }, slot: 'status' },
        {
          attrs: { label: '受理分支机构数', prop: 'access_detail_count', align: 'center' },
          slot: 'detail',
        },
        // {
        //   attrs: { label: '准入信息', align: 'center' },
        //   operations: [
        //     { content: '准入信息', icon: 'fa fa-file-text-o', event: this.handleView, ifRender: row => +row.access_status > 0 }
        //   ]
        // },
        {
          attrs: { label: '授信金额(万元)', prop: 'amount', align: 'center' },
          process: v => v || '-',
        },
      ],
      totalCount: 0,
      infoVisible: false,
      accessInfo: {},
      newVisible: false,
      newBankIds: [],

      editVisible: false,
      bankInfo: {},
      bankId: '',

      disabledNode: [],
      newable: true,

      detailVisible: false,
      queryId: '',
      seachBankId: '',
      approvalData: {},
      approvalVisible: false,
      multipleSelection: [],
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user']),
    agencyM() {
      return this.user.scopeArr.includes('agencyM')
    },
    isUserTown() {
      return +this.user.orgRegionLever > 1
    },
  },
  created() {
    this.params['bus_type.eq'] = this.type
    this.params['service_id.eq'] = this.clientId
    this.tableColumns[6].attrs.label = +this.type === 1 ? '授信金额(万元)' : '合作金额(万元)'
    this.getDisNode()
    this.getData()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBatchDelete() {
      const data = this.multipleSelection.map(item => item.credit_agency_access_id)
      if (!data.length) {
        return this.$message.warning('请先选择需要删除的银行')
      }
      // this.$api.deleteData(this.$serviceName, 'credit_agency_access', data.join(','))
      this.$utils
        .msgbox({
          message: `确定申请删除已选的${this.multipleSelection.length}个银行?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, 'credit_agency_access', data.join(',')),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除准入银行${row.agency_name}?`,
          beforeClose: () =>
            this.$api.deleteData(
              this.$serviceName,
              'credit_agency_access',
              row.credit_agency_access_id
            ),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    selectBank(bank) {
      this.params['agency_code.endlike'] = bank.agency_code
      this.getData()
    },
    handleEdit(row) {
      this.approvalData = row ? { ...row } : {}
      this.approvalVisible = true
    },
    handleDetail(row) {
      this.detailVisible = true
      this.queryId = row ? row.credit_agency_access_id : ''
    },
    handleSubmit() {
      if (!this.newBankIds.length) {
        return this.$message.warning('请先选择金融机构')
      }
      const data = []
      this.newBankIds.forEach(item => {
        data.push({
          service_id: this.clientId,
          access_agency_id: item,
          access_status: 0,
          bus_type: this.type,
          is_county_access: this.isUserTown ? 1 : 0,
        })
      })
      this.$msgbox({
        title: '提示',
        message: `确认新增所选机构 ？`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonText = '操作中...'
            instance.confirmButtonLoading = true
            await this.$api
              .addBatch(this.$serviceName, 'credit_agency_access', data)
              .then(() => {
                this.$message.success('添加成功')
                this.newBankIds = []
                this.newVisible = false
                this.getData()
                this.$store.dispatch('getAccessOrgBank')
              })
              .catch(() => {
                this.$message.error('添加失败')
              })
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            done()
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
    editCredit(data) {
      this.bankInfo = data ? { ...data } : {}
      this.bankId = data ? data.credit_agency_info_id : ''
      this.editVisible = true
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = (res && res.data) || {}
          this.tableData = (data.data || []).map(this.dataAdapter)
          this.totalCount = data.totalCount
        })
        .finally(() => {
          this.loading = false
        })
    },
    getDisNode() {
      const params = {
        'bus_type.eq': this.type,
        'agency_type.eq': 1,
        'service_id.eq': this.clientId,
      }
      this.$api.getData(this.$serviceName, this.tableName, params).then(res => {
        const data = (res && res.data) || []
        this.disabledNode = data.map(item => {
          return item.access_agency_id
        })
        this.newable = false
      })
    },
    newBank() {
      this.newVisible = true
    },
    handleView(row) {
      this.infoVisible = true
      this.accessInfo = row
    },
    dataAdapter(item) {
      item.mobile_no = item.mobile_no || ''
      const access = enumAccessStatusLabel[item.access_status] || { label: '未准入', style: 'info' }
      item.access_label = access.label
      item.access_style = access.style
      item.amount = +this.type === 1 ? item.credit_amount : item.coo_amount
      return item
    },
  },
}
</script>
<style lang="scss" scoped></style>
